<template>
  <div></div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { webThirdLoginApi, getMenuListByRole } from '/@/api/login'
import { useThemeConfig } from '/@/stores/themeConfig'
import { useChangeColor } from '/@/utils/theme'
import { initFrontEndControlRoutes } from '/@/router/frontEnd'
import { initBackEndControlRoutes } from '/@/router/backEnd'
import { Session } from '/@/utils/storage'
import { Local } from '/@/utils/storage'
import { getCompanyInfo } from '/@/api/setting/enterpriseInfo'
import { useQiyeInfo } from '/@/stores/qiyeInfo'
import { useUserInfo } from '/@/stores/userInfo'
import { getLoginUserInfoApi } from '/@/api/user'
import { NextLoading } from '/@/utils/loading'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { formatAxis } from '/@/utils/formatTime'
const stores = useQiyeInfo()
const stores2 = useUserInfo()
const router = useRouter()
const storesThemeConfig = useThemeConfig()
const { t } = useI18n()
const { themeConfig } = storeToRefs(storesThemeConfig)
const { getLightColor } = useChangeColor()
const urls = ref(window.location.href)
const getCode = async () => {
  let code
  let bindType
  let state
  let url = window.location.href
  if (url.indexOf('?') != -1 && url.indexOf('&')) {
    url = url.split('?')[1]
    var strs = url.split('&')
    for (var i = 0; i < strs.length; i++) {
      var srtArry = strs[i].split('=')
      if (srtArry[0] == 'code' || srtArry[0] == 'auth_code') {
        code = srtArry[1]
      } else if (srtArry[0] == 'bindType') {
        bindType = srtArry[1]
      } else if (srtArry[0] == 'state') {
        state = srtArry[1]
      }
    }
  }
  let params = {
    bindType: bindType,
    code: code,
    state: state
  }
  let res = await webThirdLoginApi(params)
  if (res.code == 0) {
    if (res.data.token == '') {
      router.push({
        name: 'login',
        query: {
          portrait: res.data.portrait,
          realName: res.data.realName,
          thirdId: res.data.unionId,
          bindType: bindType
        }
      })
    } else {
      // 存储 token 到浏览器缓存
      Session.set('token', res.data.token)
      Session.set('shebei', res.data)
      getCompanyInfo().then((r) => {
        if (r.code == 0) {
          Session.set('qiye', r.data)
          stores.setQiyeInfos()
        }
      })
      getLoginUserInfoApi().then((res) => {
        if (res.code == 0) {
          Session.remove('shebei')
          Session.set('shebei', res.data)
          stores2.setUserInfos()
        }
      })

      let myThemeConfig = Local.get('themeConfig')
      // 字号前后端不一致  换
      let size =
        myThemeConfig.globalFontSize == '14px'
          ? 1
          : myThemeConfig.globalFontSize == '16px'
          ? 2
          : myThemeConfig.globalFontSize == '18px'
          ? 3
          : 1
      if (size != res.data.wordSize) {
        Local.remove('themeConfig')
        themeConfig.value.globalFontSize =
          res.data.wordSize == 1
            ? '14px'
            : res.data.wordSize == 2
            ? '16px'
            : res.data.wordSize == 3
            ? '18px'
            : '14px'
        Local.set('themeConfig', themeConfig.value)
        document.documentElement.style.setProperty(
          '--el-font-size-base',
          themeConfig.value.globalFontSize
        )
        if (size == 1) {
          document.documentElement.style.setProperty(
            '--next-font-size22',
            '22px'
          )
          document.documentElement.style.setProperty(
            '--next-font-size20',
            '20px'
          )
          document.documentElement.style.setProperty(
            '--next-font-size18',
            '18px'
          )
        } else if (size == 2) {
          document.documentElement.style.setProperty(
            '--next-font-size22',
            '24px'
          )
          document.documentElement.style.setProperty(
            '--next-font-size20',
            '22px'
          )
          document.documentElement.style.setProperty(
            '--next-font-size18',
            '20px'
          )
        } else if (size == 3) {
          document.documentElement.style.setProperty(
            '--next-font-size22',
            '26px'
          )
          document.documentElement.style.setProperty(
            '--next-font-size20',
            '24px'
          )
          document.documentElement.style.setProperty(
            '--next-font-size18',
            '22px'
          )
        }
      }
      let color =
        myThemeConfig.primary == '#02AD82'
          ? 1
          : myThemeConfig.primary == '#063C74'
          ? 2
          : myThemeConfig.primary == '#063C74'
          ? 3
          : 1
      if (color != res.data.themeColor) {
        Local.remove('themeConfig')
        themeConfig.value.primary =
          res.data.themeColor == 1
            ? '#02AD82'
            : res.data.themeColor == 2
            ? '#063C74'
            : res.data.themeColor == 3
            ? '#514FC2'
            : '#02AD82'
        Local.set('themeConfig', themeConfig.value)
        changeColor(themeConfig.value.primary)
      }
      Local.set('themeConfigStyle', document.documentElement.style.cssText)

      if (!themeConfig.value.isRequestRoutes) {
        // 前端控制路由，2、请注意执行顺序
        const isNoPower = await initFrontEndControlRoutes()
        signInSuccess(isNoPower, res.data.firstLoginFlag, bindType)
      } else {
        // 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
        // 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
        const isNoPower = await initBackEndControlRoutes()
        // 执行完 initBackEndControlRoutes，再执行 signInSuccess
        signInSuccess(isNoPower, res.data.firstLoginFlag, bindType)
      }
    }
  } else {
    router.push({
      name: 'login'
    })
  }
}

// 时间获取
const currentTime = computed(() => {
  return formatAxis(new Date())
})

// 登录成功后的跳转
const signInSuccess = async (
  isNoPower: boolean | undefined,
  firstLoginFlag: any,
  bindType: any
) => {
  console.log(isNoPower)
  if (isNoPower) {
    ElMessage.warning('抱歉，您没有登录权限')
    Session.clear()
  } else {
    // 初始化登录成功时间问候语
    let currentTimeInfo = currentTime.value
    // 登录成功，跳到转首页
    // 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
    const res = await getMenuListByRole()
    let path = res.data[0].menuUrl
    router.push({
      path: path,
      query: {
        firstLoginFlag: firstLoginFlag,
        bindType: bindType
      }
    })
    // 登录成功提示
    const signInText = t('message.signInText')
    ElMessage.success(`${currentTimeInfo}，${signInText}`)
    // 添加 loading，防止第一次进入界面时出现短暂空白
    NextLoading.done(2000)
    // }
  }
}

const changeColor = (c: any) => {
  themeConfig.value.primary = c
  document.documentElement.style.setProperty('--el-color-primary', c)

  // 颜色变浅
  for (let i = 1; i <= 9; i++) {
    document.documentElement.style.setProperty(
      `--el-color-primary-light-${i}`,
      `${getLightColor(c, i / 10)}`
    )
  }
}

onMounted(() => {
  NextLoading.start()
  getCode()
})
</script>
<style scoped lang="scss"></style>
